package com.sptpc.demo1.controller;

import com.sptpc.demo1.controller.requests.AddDrinkRequest;
import com.sptpc.demo1.controller.requests.ModifyDrinkRequest;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.service.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@RestController
@ResponseBody
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    private IDrinkService drinkService;

    /**
     * 查询所有的
     * 查看  get /drink
     *
     * @RequestMapping(value = "./", method=RequstMethod.Get)
     */
    @GetMapping("/")
    public List<Drink> getAll(Integer page,Integer limit) {
        PageRequest pageRequest = PageRequest.of(page-1,limit);
        return drinkService.getAllDrinks(pageRequest);
    }

    //单个查询
    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable Integer id) {
        log.info("查询到的id: {}", id);
        return Drink.builder()
                .id(2)
                .name("焦糖拿铁")
                .price(Money.parse("USD 8.00"))
                .build();
    }

    /**
     * 新增
     * pots /drink/{"name":"奶茶","price":"8.0"}
     * 直接使用model类接受用户传来的参数
     */
    @PostMapping("/")
    public Drink addNewDrink(@RequestBody @Valid AddDrinkRequest drink, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // 错误处理
            log.error("创建新饮品失败, case by:");
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.getDefaultMessage());
            }
            return null;
        } else {
            log.info("创建新饮品：{}", drink);
            Drink savedDrink=new Drink();
            BeanUtils.copyProperties(drink,savedDrink);

           drinkService.addnewDrink(savedDrink,drink.getCategoryId());
            return savedDrink;
        }


    }

    /**
     * 修改
     * put /drink/{"id":"1","price":"9.0"}
     */
    @PutMapping("/")
    public Drink modifDrink(@RequestBody ModifyDrinkRequest request) {
        log.info("修改的饮品：{}", request);
        //后期updata数据库
        //通过id查询出饮品
        Drink drink=drinkService.getDrinkById(request.getId());
        //复制前端需要修改的属性
        BeanUtils.copyProperties(request,drink);
        //更新数据库
        drinkService.updateDrink(drink);
        return drink;
    }

    /**
     * 删除
     * delete /drink/1
     */
    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id) {
        log.info("删除的id为:{}", id);
        drinkService.deleteDrinkById(id);
        return "删除成功";
    }

    /**
     * 文件上传
     * 前端必须使用html from 提交
     * 前端必须使用multipart/form-data
     */
    //这个一个数据提交表单必须使用MULTIPART_FORM_DATA_VALUE
    @PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String uploadFile(MultipartFile file) {
        log.info("参数名 {}", file.getName());
        log.info("上传文件名 {}", file.getOriginalFilename());
        log.info("上传文件大小 {}", file.getSize());


        if (!file.isEmpty()) {
            try {
                String dest = "D:\\SchoolStudy\\upload";
                String destFileName = dest + file.getOriginalFilename();
                File destFile = new File(destFileName);
                file.transferTo(destFile);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
            return "上传成功";
        } else {
            return "上传失败";
        }
    }

    /**
     * 上传以及下载
     *
     * @param file
     * @return
     */

    @PostMapping(value = "/bacth", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public List<Drink> uploadFiles(MultipartFile file) {
        List<Drink> result = new ArrayList<>();

        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(file.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                String[] args = line.split(",");
                Drink drink = Drink.builder()
                        .id(Integer.parseInt(args[0]))
                        .name(args[1])
                        .price(Money.of(CurrencyUnit.of("CNY"), Double.parseDouble(args[2])))
                        .build();
                result.add(drink);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}